import React, { FC, useEffect, useState } from 'react';
import { history, Link, useLocation } from 'umi';
import { setLocalStorageInfo } from '@/utils/localStorageInfo';

import type { AppMenu } from '../../../stores/BsinLayoutContext';

import { getUserMenuTreeByAppCode } from '@/services/appMenu';
import { message } from 'antd';
import CompSubmenu from '../submenu';

import './index.less';
import logo2 from '@/assets/logo3.png';
import jiujiu from '@/assets/jiujiu.png';
import logoutIcon from '@/assets/logout.png';

import Fullscreen from '@/layouts/components/TopHeader/HeaderUser/Fullscreen/bsinIndex';

const MenuItem = (props: {
  img: string;
  tips?: string;
  active?: boolean;
  handleClick: (code: string) => void;
  code: string;
}) => {
  const { img, tips = '', active = false, handleClick, code } = props;

  return (
    <li
      className={`menu-item ${active ? 'active' : ''}`}
      onClick={() => handleClick(code)}
    >
      <div className="menu-icon">
        <img src={img} />
      </div>
      {tips !== '' && (
        <div className="menu-tips">
          <span>{tips}</span>
        </div>
      )}
    </li>
  );
};

interface MenuProps {
  apps: any;
}

const Menu: FC<MenuProps> = ({ apps }) => {
  // 子应用信息
  const [appMenu, setAppMenu] = React.useState<AppMenu | null>(null);
  // 子应用Code
  const [appCode, setAppCode] = useState<string>('');
  const location = useLocation();
  // 页面加载时获取是否有缓存的appCode
  useEffect(() => {
    const appC = sessionStorage.getItem('appCode_1');
    console.log(location.pathname, 'location.pathname');
    if (
      appC &&
      location.pathname != '/workplace' &&
      location.pathname != '/'
    ) {
      setLocalStorageInfo('bsin-microAppMount', '0');
      // 获取应用菜单
      setAppCode(appC);
      getUserApplicationMenu(appC);
      // 用户点击应用跳转首页
      history.push(location.pathname);
    }
  }, []);
  // 获取用户子应用菜单
  const getUserApplicationMenu = async (appCode: string) => {
    if (appCode === '') {
      setAppMenu(null);
      return;
    }
    let res = await getUserMenuTreeByAppCode({ appCode });
    if (res && res.data[0]) {
      setAppMenu(res.data[0]);
    }else{
      history.push("/workplace")
    }
    // else {
    //   message.error(`你没有${appCode}菜单权限`);
    // }
  };

  /**
   * 点击获取子应用菜单
   * @param app
   */
  const getMenu = (appCode: string) => {
    setLocalStorageInfo('bsin-microAppMount', '0');
    // 获取应用菜单
    setAppCode(appCode);
    getUserApplicationMenu(appCode);
    // 用户点击应用跳转首页
    history.push("/" + appCode);
    sessionStorage.setItem('appCode_1', appCode);
  };

  const backHome = async () => {
    setAppCode('');
    sessionStorage.removeItem('appCode_1');
    history.push('/workplace');
  };

  const logout = async () => {
    history.push('/login');
  };

  useEffect(() => {
    getUserApplicationMenu(appCode);
  }, [appCode]);

  // console.log(apps);

  return (
    <>
      <div className="menu ">
        <div className="menu-logo">
          <img src={logo2} onClick={backHome} />
        </div>
        <ul className="menu-list">
          {apps.appList.map((item: any) => (
            <MenuItem
              key={item.appName}
              handleClick={getMenu}
              code={item.appCode}
              tips={item.appName}
              active={appCode === item.appCode}
              img={item.logo}
            />
          ))}
          <li className="menu-item cockpit">
            <div className="menu-icon">
              <Fullscreen />
            </div>
          </li>
          <li className="menu-item logout">
            <div className="menu-icon" onClick={() => logout()}>
              <img src={logoutIcon} />
            </div>
          </li>
        </ul>
      </div>
      {!!appMenu && <CompSubmenu appMenus={appMenu} />}
    </>
  )
};

export default Menu;
